package com.atguigu.gmall.mq.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.mq.config.DeadLetterMqConfig;
import com.atguigu.gmall.mq.config.DelayedMqConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author LEO
 * @Date 2021年12月21日 20:01
 */
//发送确认消息测试
@RestController
@RequestMapping("/mq")
@Slf4j
public class MqController {

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    //发送消息  localhost:8282/mq/sendConfirm
    @GetMapping("sendConfirm")
    public Result sendConfirm(){
       // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //发送消息
        rabbitService.sendMessage("exchange.confirm","routing.confirm","您来晚了，没有服务了！");
        return Result.ok();
    }


    // 死信测试  发送消息  localhost:8282/mq/sendDeadLetter
    @GetMapping("sendDeadLetter")
    public Result sendDeadLetter(){
        //需要知道系统当前时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("发送时间： \t"+sdf.format(new Date()));
        // 设置发送消息
        rabbitService.sendMessage(DeadLetterMqConfig.exchange_dead,DeadLetterMqConfig.routing_dead_1,"您来晚了，没有服务了！");
        return Result.ok();
    }


    //基于插件 延迟消息测试  发送消息  localhost:8282/mq/sendDelay
    @GetMapping("sendDelay")
    public Result sendDelay(){
        //需要知道系统当前时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("发送时间： \t"+sdf.format(new Date()));
        // 设置发送消息
       // rabbitService.sendMessage(DeadLetterMqConfig.exchange_dead,DeadLetterMqConfig.routing_dead_1,"您来晚了，没有服务了！");
        rabbitTemplate.convertAndSend(DelayedMqConfig.exchange_delay, DelayedMqConfig.routing_delay, "来得真早，提前享受。。。", new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                // 设置延迟时间
                message.getMessageProperties().setDelay(10000);
                System.out.println("发送时间： \t"+sdf.format(new Date()));
                return message;
            }
        });
        return Result.ok();
    }
}
